﻿<template>
  <div class="app-container">
    <div class="chart-title with-back">
      <div class="chart-left">
        <div>档案管理</div>
        <div class="backtrack">
          <el-button @click="comeBack">返回</el-button>
        </div>
      </div>
    </div>
    <div class="info-items">
      <div class="info-title">送餐日期： {{ currentDate }}</div>
      <div>
        <el-form
          ref="baseForm"
          :model="chartData"
          label-position="right"
          label-width="150px"
          size="small"
        >
          <div class="base-from">
            <el-form-item :label="$t('supplier.name')+':'">
              <el-input
                v-model="chartData.supplier_name"
                :readonly="true"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('goods.name')+':'">
              <el-input
                v-model="chartData.goods_name"
                :readonly="dialogStatus === 'edit' ? false:true"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('public.mobile')+':'">
              <el-input-number
                class="left-number"
                v-model="chartData.cost_price"
                :controls="false"
              ></el-input-number>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="nav-bar"></div>
    <div class="terminalList">
      <div class="table-content">
        <div class="info-content">
          <div class="info-title">设备</div>
          <div
            class="new-staff"
            @click="handleCreate"
          >
            <div class="add-buttom">
              <i class="el-icon-circle-plus"></i>
            </div>
            <div class="add-name">增加设备</div>
          </div>
        </div>
        <el-table
          :data="chartData.list"
          border
          :header-cell-style="{background:'#F2F1F6',color:'#8B94BE'}"
          style="width: 100%"
        >
          <el-table-column
            :label="$t('terminal.name')"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.equipment_name }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('terminal.alias')"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.alias }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('public.location')"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.address }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('order.bookNumber')"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.reserve_number }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('order.sitesNumber')"
            align="center"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.estimate_number"
                :min="0"
                :step="1"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('order.sumNumber')"
            align="center"
          >
            <template slot-scope="scope">
              {{ allNumber(scope.row.reserve_number, scope.row.estimate_number) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('public.money')"
            align="center"
          >
            <template slot-scope="scope">
              {{ allMoney( allNumber(scope.row.reserve_number, scope.row.estimate_number), chartData.cost_price) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="order-mess">
          <div class="order-number">订单数量: {{ countAll }}份</div>
          <div class="order-cost">订单金额: {{ allCost }}元</div>
        </div>
      </div>
      <div class="table-banner"></div>
      <div class="statistics">
        <div
          class="statistics-left"
          style="width:400px;display:flex"
        >
          <div style="width:120px;display:flex;align-items: center;">备注信息: </div>
          <el-input v-model="chartData.remark"></el-input>
        </div>
        <div class="statistics-right">
          <div
            class="submit-button"
            @click="submitData()"
          >提交</div>
        </div>
      </div>
    </div>
    <!-- 编辑 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        @submit.native.prevent
      >
        <div class="pops">
          <div class="pops-normal">
            <el-form-item
              :label="$t('terminal.name')"
              prop="equipment_id"
            >
              <el-select
                v-model="temp.equipment_id"
                multiple
                collapse-tags
                style="margin-left: 20px;"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in newEqiupmentOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <div
              slot="footer"
              class="dialog-footer between-space"
            >
              <div>
              </div>
              <div>
                <el-button @click="dialogVisible = false">{{ $t("table.cancel") }}</el-button>
                <el-button
                  type="primary"
                  @click="createData()"
                >{{ $t("table.confirm") }}</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth";
export default {
  name: "PurchaseRequisition",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    return {
      chartData: {
        supplier_id: undefined,
        supplier_name: "",
        goods_id: undefined,
        goods_name: "",
        cost_price: "",
        list: []
      },
      currentDate: "",
      index_id: undefined,
      dialogVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        equipment_id: [{ required: true, message: "请选择设备", trigger: "change" }]
      },
      temp: {
        equipment_id: undefined,
        equipment_name: "",
        itoc_id: undefined,
        itoc_name: "",
        address: "",
        goods_id: undefined,
        goods_name: "",
        reserve_number: undefined,
        estimate_number: undefined,
        cost_price: ""
      },
      newEqiupmentOption: []
    };
  },
  computed: {
    countAll: function() {
      let all = 0;
      const data = this.chartData.list;
      data.forEach(element => {
        console.log('element', element)
        all += parseInt(this.allNumber(element.reserve_number, element.estimate_number))
      })
      return all;
    },
    allCost: function() {
      let all = 0;
      const data = this.chartData.list;
      data.forEach(element => {
        console.log('element', element)
        all += parseInt(this.allNumber(element.reserve_number, element.estimate_number)) * this.chartData.cost_price
      })
      return all.toFixed(2);
    }
  },
  created() {
    const token = getToken()
    if (token && !this.$store.state.socket.loginTransition && !this.$store.state.socket.loginAccount) {
      this.tokenLogin(token)
    }
    this.currentDate = this.timestampToTime(new Date().getTime(), '{y}-{m}-{d}');
    this.ids = this.$route.query.ids
    const mes = this.$route.query.mes
    if (this.ids) {
      this.getList();
    } else if (mes) {
      this.chartData = JSON.parse(mes)
    }
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    getList() {
      this.listLoading = true;
      const path = {
        app: "subscribe",
        api: "api_subscribe_index_createGoodsOrder",
        version: "1.0",
        type: 2,
        data: {
          ids: this.ids ? this.ids : ""
        }
      }
      console.log('JSON.stringify(path)', JSON.stringify(path))
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    comeBack() {
      this.$router.push({ path: '/orders/book-list' })
    },
    createData() {
      const option = this.newEqiupmentOption;
      const newOption = [];
      option.forEach(element => {
        console.log('element', element)
        const _this = this
        if (_this.temp.equipment_id.indexOf(element.id) !== -1) {
          newOption.push({
            equipment_id: element.id,
            equipment_name: element.name,
            alias: element.alias,
            address: element.address,
            reserve_number: 0,
            estimate_number: 0
          })
        }
      })
      this.$set(this.chartData, 'list', this.chartData.list.concat(newOption));
      this.dialogVisible = false;
    },
    submitData() {
      const path = {
        app: "buy",
        api: "api_buy_index_addBuy",
        version: "1.0",
        type: "1,2",
        data: this.chartData
      }
      console.log('JSON.stringify(path)', JSON.stringify(path))
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    allNumber(book, estimate) {
      let all = 0
      if (book && estimate) {
        all = parseInt(book) + parseInt(estimate);
      } else if (!book && estimate) {
        all = estimate
      } else {
        all = book
      }
      return all
    },
    allMoney(number, price) {
      return number * price.toFixed(2)
    },
    handleCreate(index) {
      this.index_id = index;
      const path = {
        app: "equipment",
        api: "api_equipment_index_getList",
        version: "1.0",
        data: {
          supplier_name: this.chartData.supplier_name
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            })
          } else if (resj.api === "api_subscribe_index_createGoodsOrder") {
            const data = resj.data;
            if (data.list && data.list.length > 0) {
              data.remark = ""
              data.list.forEach(element => {
                element.estimate_number = 0;
              })
            }
            this.chartData = data;
          } else if (resj.api === "api_buy_index_addBuy") {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 1000
            });
            setTimeout(() => {
              this.$router.push({ path: '/purchase-data/purchase-requisition-list' })
            }, 1000);
          } else if (resj.api === "api_equipment_index_getList") {
            // 已有设备
            const equipment = this.chartData.list;
            const equipment_id = [];
            equipment.forEach(res => {
              equipment_id.push(res.equipment_id)
            })
            // 新增设备
            const newEqiupment = resj.data
            const data = [];
            newEqiupment.forEach(element => {
              if (equipment_id.indexOf(element.id) === -1) {
                data.push(element)
              }
            })
            this.newEqiupmentOption = data;
            if (this.newEqiupmentOption.length > 0) {
              this.dialogVisible = true;
              this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
              });
            } else {
              this.$message.error('没有更多设备');
            }
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.warehouse-info {
  display: flex;
  padding: 14px;
}
.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 14px;
}
.warehouse-info div {
  flex: 1;
}
.action-right {
  display: flex;
}
.action-right div:not(:first-child) {
  margin-left: 14px;
}
.terminalList {
  background-color: #ffffff;
  border-radius: 4px;
  margin-bottom: 24px;
}
.terminalList .table-content {
  padding: 0 16px 16px 16px;
}
.info-items {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  padding: 16px;
}
.nav-bar {
  height: 8px;
  background: rgba(240, 242, 245, 1);
}
.base-from {
  padding-top: 20px;
  display: flex;
  align-items: center;
}
.base-from div {
  flex: 1;
}
.order-mess {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  line-height: 1;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(51, 51, 51, 1);
}
.order-cost {
  margin-left: 40px;
}
.info-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  line-height: 1;
}
.new-staff {
  display: flex;
  align-items: center;
}
.new-staff:hover .el-icon-circle-plus,
.new-staff:hover .add-name {
  display: flex;
  align-items: center;
  color: #2d67e8;
}
.add-buttom {
  display: flex;
  align-items: center;
}
.add-name {
  margin-left: 4px;
}
.submit-button {
  width: 72px;
  height: 32px;
  background: rgba(45, 65, 152, 1);
  border-radius: 16px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
